import {
  getSongDetail
} from "../../api/detail";
const audioContext = wx.createInnerAudioContext()

// pages/music-player/music-player.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentSong: {},
    currentPage: 0,
    currentTime: 0,
    durationTime: 0,
    sliderValue: 0,
    isChange: false,
    isPlay: true,
    playType: 'pause'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options.id);
    const id = options.id
    this.onGetSongDetail(id)

    // 音频处理
    audioContext.src = `https://music.163.com/song/media/outer/url?id=${id}.mp3`
    audioContext.stop()
    audioContext.onCanplay(() => {
      audioContext.play()
    })

    // 音频更新
    audioContext.onTimeUpdate(() => {
      // console.log(audio.currentTime);
      const currentTime = audioContext.currentTime * 1000
      const sliderValue = currentTime / this.data.durationTime * 100
      // console.log(currentTime);
      if (!this.data.isChange) {
        this.setData({
          currentTime,
          sliderValue
        })
      }
    })
  },

  // 获取歌曲信息
  async onGetSongDetail(ids) {
    const res = await getSongDetail(ids)
    // console.log(res);
    this.setData({
      currentSong: res.songs[0],
      durationTime: res.songs[0].dt
    })
  },

  // 处理页面滚动
  handleSwiperChange(e) {
    const current = e.detail.current
    this.setData({
      currentPage: current
    })
  },
  // 进度条正在发生滑动
  handleSliderChanging(e) {
    const value = e.detail.value
    const currentTime = this.data.durationTime / 100 * value
    this.setData({
      isChange: true,
      currentTime
    })
  },

  // 进度条滑动
  handleSilderChange(e) {
    const value = e.detail.value

    const currentTime = this.data.durationTime / 100 * value
    audioContext.pause()
    audioContext.seek(currentTime / 1000)

    this.setData({
      sliderValue: value,
      isChange: false,
      isPlay: true,
      playType: "pause"
    })
  },

  // 播放/暂停
  onPlayMusic() {
    const isPlay = !this.data.isPlay
    const playType = isPlay ? "pause" : "resume"
    this.setData({
      isPlay,
      playType
    })
    if (isPlay) {
      audioContext.play()
    } else {
      audioContext.pause()
    }
  }
})
